package com.controller.user;

import com.dto.LoginDto;
import com.pojo.User;
import com.service.LoginService;
import com.utils.JwtUtil;
import com.utils.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping()
@Api(tags = "登录相关接口")
public class LoginController {
    @Autowired
    LoginService loginService;

    /**
     * 用户登录
     * @param loginDto
     * @return
     */
    @PostMapping("/login")
    @ApiOperation("用户登录")
    public Result<String> Login(@RequestBody LoginDto loginDto) {
        User user=loginService.login(loginDto);
        if(user!=null){
            Map<String,Object> claims=new HashMap<>();
            claims.put("id",user.getId());
            claims.put("name",user.getName());
            claims.put("username",user.getPassword());
            String jwt = JwtUtil.createJWT(claims);
            return Result.success(jwt);
        }
        return Result.error("用户名或密码错误");

    }

    /**
     * 用户注册
     * @param loginDto
     * @return
     */
    @PostMapping("/register")
    @ApiOperation("用户注册")
    public Result<String> register(@RequestBody LoginDto loginDto) {
        loginService.register(loginDto);
        return Result.success("注册成功");
    }


}
